package com.wxm.killing.mq.common.exception;

import com.wxm.killing.mq.common.enums.HttpStatusEnum;
import com.wxm.killing.mq.common.model.JsonResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * @Description TODO
 * @author: wxm
 * @date: 2019/10/10 8:29
 * @version: 1.0
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 参数校验异常
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public JsonResult methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        logger.error("occurs error " + errInfo(e));
        JsonResult jsonResult = new JsonResult();
        jsonResult.setStatus(HttpStatusEnum.BAD_REQUEST.getStatus());
        jsonResult.setMsg(e.getBindingResult().getFieldError().getDefaultMessage());
        return jsonResult;
    }

    /**
     * 系统错误
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public JsonResult exceptionHandler(Exception e) {
        logger.error("occurs error " + errInfo(e));
        JsonResult jsonResult = new JsonResult();
        jsonResult.setStatus(HttpStatusEnum.INTERNAL_SERVER_ERROR.getStatus());
        jsonResult.setMsg(HttpStatusEnum.INTERNAL_SERVER_ERROR.getMsg());
        return jsonResult;
    }


    /**
     * 手动抛出异常
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = BaseException.class)
    public JsonResult baseExceptionHandler(BaseException e) {
        logger.error("occurs error " + errInfo(e));
        JsonResult jsonResult = new JsonResult();
        jsonResult.setStatus(e.getErrStatus());
        jsonResult.setMsg(e.getErrMsg());
        return jsonResult;
    }

    private String errInfo(Exception e) {
        StringWriter sw = null;
        PrintWriter pw = null;
        try {
            sw = new StringWriter();
            pw = new PrintWriter(sw);
            // 将出错的栈信息输出到printWriter中
            e.printStackTrace(pw);
            pw.flush();
            sw.flush();
        } finally {
            if (sw != null) {
                try {
                    sw.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (pw != null) {
                pw.close();
            }
        }
        return sw.toString();
    }

}
